const log4js      = require('../../data/log');
const logger      = log4js.getLogger('info');
const settingModel = require("../../model/setting");
const constants   = require('../../data/constants');
const fs          = require('fs');
const request     = require("request");
const ffmpeg        = require('fluent-ffmpeg');
module.exports={
    /**
     * TODO: 准备换成httpUtils
     * 调用zlmediakit 进行截图操作，暂时不用
     */
    snap0(query,deviceid,channel){
        return new Promise(function (resolve) {
            let url = constants.zlmedia.url + 'index/api/getSnap';
            let param = "?" + query;
            let path = settingModel.cache.snap_path + "/" + deviceid + "_" + channel + ".jpg";
            request(url + param).pipe(fs.createWriteStream(path));
            resolve({});
        });
    },

    /**
     * 使用fluent-ffmpeg截图
     */
    snap(source, deviceid, channel){
        logger.info('snap to' ,settingModel.cache.snap_path , deviceid + "_" + channel + ".jpg", 'source', source);

        return new Promise(function (resolve, reject) {
            if(!channel || channel==='undefined'){
               reject();
               return;
            }
            ffmpeg({source: source, timeout: 20})
                .on('filenames', function (filenames) {
                    let ret = settingModel.cache.snap_path || '';
                    let last = ret.charAt(ret.length - 1);
                    if (last !== '/') ret = ret + '/';
                    let first = ret.charAt(0);
                    if (first === '.') ret = ret.substring(1, ret.length);
                    if (ret.indexOf('/public') === 0) {
                        ret = ret.replace('/public', '');
                    }
                    resolve(ret + filenames);
                })
                .on('end', function () {
                    logger.log('ffmpeg end');
                })
                .on('stderr', function (stderrLine) {
                    logger.log('Stderr output: ' + stderrLine);
                })
                .on('error', function (err) {
                    logger.log('Cannot process video: error =', err.message);
                }).addOption(['-rtsp_transport tcp'])
                .screenshots({
                    count: 1,
                    // timemarks: [ '00:00:02.000' ],
                    folder: settingModel.cache.snap_path,
                    filename: deviceid + "_" + channel + ".jpg",
                    size: '640x?',
                    timeout: 20
                });
        });
    }
};
